package comanche.cmd;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Iterator;

public class CommandLoader {
	private ArrayList<ICmd> commands = new ArrayList<ICmd>();
	
	public CommandLoader(String commandPath) {
		try {
			LoadCommands(commandPath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public String executeAllCommands(File file) {

		Iterator i = commands.iterator();	
		String temp = "";
	    while (i.hasNext()) {
	    	temp += "<td>" + ((ICmd)i.next()).process(file) + "</td>";
	    }
	    return temp;
	}

	ArrayList<ICmd> LoadCommands(String command_path)
			throws FileNotFoundException {

		File cmd_folder = new File(command_path);
		if (!cmd_folder.exists() || !cmd_folder.isDirectory())
			throw new FileNotFoundException();

		// Getting all the directory's children as URLs
		URL[] urls = FilesToURL(cmd_folder.listFiles());

		URLClassLoader classLoader = new URLClassLoader(urls);

		for (File file : cmd_folder.listFiles()) {
			String className = getClassName(file);

			// Not a java class
			if (className == null) {
				System.out.println(file.getName()
						+ " is not a valid Java class. Skipping.");
			} else {
				System.out.println("Loading command: " + className);

				try {
					Class c = classLoader.loadClass(className);
					commands.add((ICmd) c.newInstance());
				} catch (Exception ex) {
				}
			}
		}

		return commands;
	}

	private URL [] FilesToURL(File [] files) {
	
	    URL[] urls = new URL[files.length];
	
	    for( int i = 0 ; i < files.length ; ++i )
	    {
	        System.out.println(files[i].getName() + " found.");
	        try {
	            urls[i] = files[i].toURI().toURL();
	        } catch (MalformedURLException ex) {
	        }
	    }
	
	    return urls;
	}
	
    private String getClassName(File file) {
        String cn = file.getName();
        String ext = (cn.lastIndexOf(".")==-1)?"":cn.substring(cn.lastIndexOf(".")+1,cn.length());

        if( ext.isEmpty() || !ext.equals("class") )
            return null;
        
        return "comanche." + cn.substring(0, cn.lastIndexOf("."));
    }

}
